/**
 * @since : 2018/3/26 下午2:34
 * @author : fupeng
 */

class Mutil{
    request(params) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: params.url || '',
                type: params.type || 'get',
                dataType: params.dataType || 'json',
                data: params.data || {},
                success: res => {
                    if (0 === res.status) {
                        typeof resolve === 'function' && resolve(res.data || res.msg);
                    } else if (10 === res.status) {
                        Mutil.doLogin();
                    } else {
                        typeof reject === 'function' && reject(res.data || res.msg);
                    }
                },
                error: err => {
                    console.log(res.status);
                }
            });
        });
    }

    static doLogin(){
        window.location = '/login?redirect=' + encodeURIComponent(window.location.pathname);
    }

    // 获取URL中指定的参数
    static getParamFromUrl(name) {
        let queryStr = window.location.search.split("?")[1] || '',
            reg = new RegExp("(^|$)" + name + "=([^&]*)(&|$)"),
            result = queryStr.match(reg);

        return result && result.length > 2 ? result[2] : "";
    }

    static errorTips(errorMsg) {
        alert(errorMsg);
    }

    // 保存localsStorage
    static setLocalStorage(name, data) {
        let dataType = typeof data;
        if (dataType === 'object') {
            window.localStorage.setItem(name, JSON.stringify(data));
        } else if (['number', 'string', 'boolean'].indexOf(dataType) >= 0) {
            window.localStorage.setItem(name, data);
        } else {
            alert('数据无法本地存储');
        }
    }

    // 获取localStorage
    static sgetLocalStorage(name) {
        let data = window.localStorage.getItem(name);
        if (data) {
            return JSON.parse(data);
        } else {
            return "";
        }
    }

    // 删除 locaStorage
    static removeLocalStorage(name) {
        window.localStorage.removeItem(name);
    }
}

export default Mutil;